// 这个文件，专门处理商品相关的
const express = require("express");
const router = express.Router();
var ObjectId = require("mongodb").ObjectId;
const GoodsModel = require("../models/goods");
const path = require("path");
const fs = require("fs");
const multer = require("multer");
const upload = multer({
  dest: "./uploads"
});

const imgurl='106.53.0.92'

// 添加商品 传参:goodsName,imgUrl,price(必填)  marketPrice,stock(选传)
router.post("/addGoodsInfo", async (req, res) => {
  const goodsName = req.body.goodsName;
  const imgUrl = req.body.imgUrl;
  const price = req.body.price;
  const marketPrice = req.body.marketPrice || price;
  const stock = req.body.stock || 0;
  console.log(goodsName, imgUrl, price, marketPrice, stock);

  const goods = new GoodsModel({
    goodsName,
    imgUrl,
    price,
    marketPrice,
    stock
  });
  await goods.save();
  res.send({
    code: 0,
    msg: "添加商品成功"
  });
});

// 删除商品 传参:goodsId
router.post("/delGoodsInfo", async (req, res) => {
  const goodsId = req.body.goodsId;

  await GoodsModel.deleteOne({ _id: ObjectId(goodsId) }, { justOne: true });

  res.send({
    code: 0,
    msg: "删除成功"
  });
});

// 查询所有商品 不需要传参
router.post("/findAllGoodsInfo", async (req, res) => {
  const goodsList = await GoodsModel.find();
  let data = goodsList;
  res.send({
    code: 0,
    msg: "查询成功",
    data
  });
});

// 根据商品名称模糊查询 传参:goodsName
router.post("/findGoodsByName", async (req, res) => {
  const goodsName = req.body.goodsName;
  const goodsList = await GoodsModel.find({
    $or: [{ goodsName: { $regex: goodsName } }]
  });
  let data = goodsList;
  res.send({
    code: 0,
    msg: "查询成功",
    data
  });
});

// 修改商品信息 传参:goodsId(key/_id)(必要) goodsName imgUrl price marketPrice stock (根据需求传)
router.post(
  "/upDateGoods",
  upload.fields([
    { name: "imgfile", maxCount: 3 },
    { name: "file", maxCount: 8 }
  ]),
  async (req, res) => {
    const info = JSON.parse(req.body.info);

    const goodsId = info.key;
    let thumbnailList = info.imgUrl ? JSON.parse(info.imgUrl) : [];
    let imgList = info.infoImgUrl ? JSON.parse(info.infoImgUrl) : [];
    // 缩略图
    if (req.files.imgfile) {
      req.files.imgfile.forEach((value, index) => {
        const fileData = fs.readFileSync(
          path.resolve(__dirname, "../uploads/", value.filename)
        );
        let type = value.originalname.split(".")[1];
        const filename = new Date().getTime() + "-" + index + "." + type;
        const filePath = path.resolve(__dirname, "../public/", filename);
        fs.writeFileSync(filePath, fileData);
        thumbnailList.push("http://localhost:8080/" + filename);
      });
    }
    // 详细信息图
    if (req.files.file) {
      req.files.file.forEach((value, index) => {
        const fileData = fs.readFileSync(
          path.resolve(__dirname, "../uploads/", value.filename)
        );
        let type = value.originalname.split(".")[1];
        const filename = new Date().getTime() + "-" + index + "." + type;
        const filePath = path.resolve(__dirname, "../public/", filename);
        fs.writeFileSync(filePath, fileData);
        imgList.push("http://localhost:8080/" + filename);
      });
    }
    // console.log(req.body);
    // console.log(thumbnailList);
    // console.log(imgList);
    const goodsName = info.goodsName;
    const imgUrl = JSON.stringify(thumbnailList);
    const infoImgUrl = JSON.stringify(imgList);
    const price = info.price;
    const marketPrice = info.marketPrice || price;
    const stock = info.stock || 0;

    // console.log(goodsName, imgUrl, infoImgUrl, price, marketPrice, stock);

    await GoodsModel.updateOne(
      { _id: goodsId },
      { $set: { goodsName, imgUrl, infoImgUrl, price, marketPrice, stock } }
    );

    res.send({
      code: 0,
      msg: "修改成功"
    });
  }
);

// 添加商品信息
router.post(
  "/addGoodsInfos",
  upload.fields([
    { name: "imgfile", maxCount: 3 },
    { name: "file", maxCount: 8 }
  ]),
  async (req, res) => {
    console.log(req.body);
    console.log(req.files);
    let thumbnailList = [];
    let imgList = [];
    // 缩略图
    if (req.files.imgfile) {
      req.files.imgfile.forEach((value, index) => {
        const fileData = fs.readFileSync(
          path.resolve(__dirname, "../uploads/", value.filename)
        );
        let type = value.originalname.split(".")[1];
        const filename = new Date().getTime() + "-" + index + "." + type;
        const filePath = path.resolve(__dirname, "../public/", filename);
        fs.writeFileSync(filePath, fileData);
        thumbnailList.push("http://localhost:8080/" + filename);
      });
    }

    // 详细信息图
    if (req.files.file) {
      req.files.file.forEach((value, index) => {
        const fileData = fs.readFileSync(
          path.resolve(__dirname, "../uploads/", value.filename)
        );
        let type = value.originalname.split(".")[1];
        const filename = new Date().getTime() + "-" + index + "." + type;
        const filePath = path.resolve(__dirname, "../public/", filename);
        fs.writeFileSync(filePath, fileData);
        imgList.push("http://localhost:8080/" + filename);
      });
    }
    console.log(JSON.parse(req.body.info));
    const info = JSON.parse(req.body.info);
    console.log(thumbnailList);
    console.log(imgList);
    const goodsName = info.goodsName;
    const imgUrl = JSON.stringify(thumbnailList);
    const infoImgUrl = JSON.stringify(imgList);
    const price = info.price;
    const marketPrice = info.marketPrice || price;
    const stock = info.stock || 0;
    console.log(goodsName, imgUrl, infoImgUrl, price, marketPrice, stock);

    const goods = new GoodsModel({
      goodsName,
      imgUrl,
      infoImgUrl,
      price,
      marketPrice,
      stock
    });
    await goods.save();
    res.send({
      code: 0,
      msg: "添加商品成功",
      data: goods
    });
  }
);

module.exports = router;
